<!-- Datatables -->
<link href="/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet">

<!-- 上传图片 -->
<link href="/vendors/fileinput/fileinput.min.css" rel="stylesheet" />

<!-- page content -->
<div id="modules" class="right_col" role="main">
    <div class="">
        <div class="page-title">
            <div class="title_left">
                <h3>Users <small>Some examples to get you started</small></h3>
            </div>
        </div>

        <div class="clearfix"></div>

        <div class="row">
            <div class="col-md-12 col-sm-12 ">
                <div class="x_panel">
                    <div class="x_title">
                        <!-- Large modal -->
                        <button @click="initAddModule()" type="button" class="btn btn-primary" data-toggle="modal"
                                data-target="#addModule">新增</button>
                        <ul class="nav navbar-right panel_toolbox">
                            <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                            </li>
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
                                   aria-expanded="false"><i class="fa fa-wrench"></i></a>
                                <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                    <a class="dropdown-item" href="#">Settings 1</a>
                                    <a class="dropdown-item" href="#">Settings 2</a>
                                </div>
                            </li>
                            <li><a class="close-link"><i class="fa fa-close"></i></a>
                            </li>
                        </ul>
                        <div class="clearfix"></div>
                    </div>
                    <div class="x_content">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="card-box table-responsive">
                                    <table id="moduleTable" class="table table-striped table-bordered"
                                           style="width:100%">
                                        <thead>
                                        <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>UserName</th>
                                            <th>Email</th>
                                            <th>UserImage</th>
                                            <th>CreateDate</th>
                                            <th>Operation</th>
                                        </tr>
                                        </thead>
                                        </thead>


                                        <tbody>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div th:replace="/account/userAdd.html">

    </div>
</div>
<!-- /page content -->


<!-- Datatables -->
<script src="/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>

<!-- 上传图片 -->
<script src="/vendors/fileinput/fileinput.min.js" type="text/javascript"></script>
<!-- bootstrap-progressbar -->
<script src="/vendors/bootstrap-progressbar/bootstrap-progressbar.min.js" type="text/javascript"></script>

<script>
    new Vue({
        el: "#modules",
        data: {
            //默认页长
            defaultPageSize: 5,
            //表格数据结构
            tableData: {
                draw: 0,
                recordsTotal: 0,
                recordsFiltered: 0,
                data: []
            },
            module:{
                roleId:0,
                userName:"",
                password:"",
                userImage:"",
                roles:[],//当前用户选择的用户列表
            },
            //所有的角色列表
            roles: [],
        },
        methods: {
            //行数据结构
            rowData: function (id, userName, email,userImage, createDate) {
                var row = {};
                row.id = id;
                row.userName = userName;
                row.email = email;
                // row.userImage = userImage;
                row.userImage = function (){
                    if (userImage == null || userImage == ""){
                        return "";
                    }
                    return "<image src='"+userImage+"' style='width: 20px;height: 20px'/>"
                };
                row.createDate = createDate;
                row.operation = function (id) {
                    return (
                        "<a href='javascript:void(0);' class='btn_editcolor' data-toggle='modal' data-target='#editModal' " +
                        "onclick='initEditModal(\"" +
                        id +
                        "\")'>编辑</a>&nbsp;" +
                        "<a href='javascript:void(0);' onclick='deleteModule(\"" +
                        id +
                        "\")' class='btn_editcolor'>删除</a>"
                    );
                };
                return row;
            },
            //初始化表格数据
            initTable: function () {
                var self = this;
                $("#moduleTable").dataTable({
                    paging: true, //分页
                    serverSide: true, //开启后端分页
                    pagingType: "full_numbers", //分页样式的类型 simple/simple_numbers/full/full_numbers
                    pageLength: self.defaultPageSize, //定义初始的页长
                    processing: true,
                    destroy: true, //允许销毁替换，在表格重新查询时，可以自动销毁以前的data
                    lengthChange: true, //控制是否能够调整每页的条数
                    searching: true,
                    "data-show-refresh": true,
                    ordering: true,
                    autoWidth: true,
                    ajax: function (data, callback, settings) {
                        // 从data获取查询数据
                        var columIndex = data.order[0].column;
                        var direction = data.order[0].dir;
                        var orderBy = data.columns[columIndex].name;
                        pageSize = data.length == undefined ? pageSize : data.length;

                        var search = {};
                        search.currentPage = data.start / pageSize + 1;
                        search.pageSize = pageSize;
                        search.sort = orderBy;
                        search.direction = direction;
                        search.keyword = data.search.value;

                        $.ajax({
                            url: "/api/users",
                            type: "post",
                            contentType: "application/json",
                            data: JSON.stringify(search),
                            success: function (rs) {
                                if (!rs) {
                                    layer.alert("请求出错，请稍后重试" + rs.errmsg, {icon: 2});
                                    callback(self.tableData);
                                    return;
                                }
                                if (rs.list == null) {
                                    $("#moduleTable tbody tr").remove();
                                    $("#loading").remove();
                                    callback(self.tableData);
                                    return;
                                }
                                $("#loading").remove();
                                var rowsData = [];
                                for (var i = 0; i < rs.list.length; i++) {
                                    //包装行数据
                                    var row = self.rowData(
                                        rs.list[i].userId,
                                        rs.list[i].userName,
                                        rs.list[i].email,
                                        rs.list[i].userImage,
                                        rs.list[i].createDate
                                    );
                                    // 将行数据放到数组里
                                    rowsData.push(row);
                                }
                                self.tableData.data = rowsData;
                                self.tableData.recordsTotal = rs.total;
                                self.tableData.recordsFiltered = rs.total;
                                callback(self.tableData);
                            },
                            error: function (data) {
                                layer.alert(data.responseText, {icon: 0});
                            },
                        });
                    },
                    columns: [
                        //定义行数据字段
                        {data: "id", name: "id", sortable: true},
                        {data: "userName", name: "user_name", sortable: true},
                        {data: "email", name: "email", sortable: true},
                        {data: "userImage", name: "user_image", sortable: true},
                        {data: "createDate", name: "create_date", sortable: true},
                        {data: "operation", width: "80px", sortable: false},
                    ],
                });
            },

            //初始化module
            initAddModule:function (){
                this.module={
                    roleId:0,
                    userName:"",
                    password:"",
                    userImage:"",
                    roles:[],//当前用户选择的用户列表
                }
            },

            //图片组件
            initFileInput: function () {
                var self = this;
                $("#uploadImage")
                    .fileinput({
                        uploadUrl: "/api/image/profile-big",
                        enctype: "multipart/form-data",
                        previewFileType: "image",
                        uploadAsync: true,
                        allowedFileExtensions: ["png", "jpg", "jpeg", "ico", "bmp", "gif"],
                        maxFileCount: 1,
                        maxFileSize: 3072,
                        minImageWidth: 50,
                        minImageHeight: 50,
                        maxImageWidth: 1000,
                        maxImageHeight: 1000,
                        msgFilesTooMany: "Upload file count({n} - {m})",
                        showCaption: false,
                        dropZoneEnabled: false,
                        showBrowse: true,
                        browseClass: "btn btn-primary",
                        uploadClass: "btn btn-info",
                        removeClass: "btn btn-danger",
                    })
                    .on("fileerror", function (event, data, msg) {
                        layer.alert("Upload file failed" + msg, { icon: 0 });
                    })
                    .on("fileuploaded", function (event, data) {
                        if (data.response.status == 200) {
                            self.module.userImage = data.response.data;
                        } else {
                            $(".fileinput-remove-button").click();
                        }
                        layer.alert(data.response.message, { icon: 0 });
                    })
                    .on("fileclear", function (event) {});
            },
            //插入module
            addModule:function (){
                if(this.module.userName == "" || this.module.password == ""){
                    layer.msg("请输入用户名和密码",{icon: 0});
                    return;
                }

                //数据包装
                this.module.roles = this.module.roles.map(item => {
                    var role = {};
                    role.roleId = item;
                    return role;
                })

                var self = this;
                $.ajax({
                    url:"/api/user",
                    type:"post",
                    contentType: "application/json",
                    data:JSON.stringify(self.module),
                    success:function (rs){
                        if (rs.status == 200){
                            //关闭模态框
                            $('#addModule').modal("hide");
                            self.initTable();
                        }else {
                            layer.msg(rs.message,{icon: 0});
                        }
                    },
                    error:function (rs){
                        // TODO
                    }
                })
            },

            //初始化所有的角色列表
            initRoles:function (){
                var self = this;
                $.ajax({
                    url:"/api/roles",
                    type:"get",
                    success:function (rs){
                        self.roles = rs;
                    },
                    error:function (rs){
                        // TODO
                    }
                })
            }

        },
        mounted() {
            this.initTable();
            this.initRoles();
            this.initFileInput();
        },
    });
</script>